package com.zqxx.examine.portal.controller.page;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.common.utils.PagingUtil;
import com.zqxx.examine.model.exam.ExamHistory;
import com.zqxx.examine.model.practice.KnowledgePointAnalysisResult;
import com.zqxx.examine.model.practice.TypeAnalysis;
import com.zqxx.examine.model.question.Field;
import com.zqxx.examine.model.question.QuestionStatistic;
import com.zqxx.examine.portal.security.UserInfo;
import com.zqxx.examine.portal.service.ExamService;
import com.zqxx.examine.portal.service.QuestionHistoryService;
import com.zqxx.examine.portal.service.QuestionService;

@Controller
public class UserCenterPage
{
  @Autowired
  private QuestionService questionService;
  @Autowired
  private QuestionHistoryService questionHistoryService;
  @Autowired
  private ExamService examService;
  
  @RequestMapping(value={"student/usercenter"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userCenterDefaultPage(Model model, HttpServletRequest request)
  {
    List<Field> fieldList = this.questionService.getAllField(null);
    return "redirect:/student/usercenter/" + ((Field)fieldList.get(0)).getFieldId();
  }
  
  @RequestMapping(value={"student/usercenter/{fieldId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userCenterPage(Model model, HttpServletRequest request, @PathVariable int fieldId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    

    model.addAttribute("username", userInfo.getUsername());
    model.addAttribute("username", userInfo.getTrueName());
    model.addAttribute("email", userInfo.getEmail());
    model.addAttribute("field", userInfo.getFieldName());
    
    Map<Integer, QuestionStatistic> questionStatisticMap = this.questionService.getQuestionStaticByFieldId(fieldId);
    Map<Integer, QuestionStatistic> questionHistStatisticMap = this.questionHistoryService.getQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
    model.addAttribute("lastLoginTime", userInfo.getLastLoginTime());
    List<StatisticsResult> resultList = new ArrayList();
    
    List<Label> titleList = new ArrayList();
    List<Float> finishRateList = new ArrayList();
    List<Float> rightRateList = new ArrayList();
    for (Map.Entry<Integer, QuestionStatistic> entry : questionStatisticMap.entrySet())
    {
      StatisticsResult sr = new StatisticsResult();
      sr.setPointId(((QuestionStatistic)entry.getValue()).getPointId());
      sr.setPointName(((QuestionStatistic)entry.getValue()).getPointName());
      sr.setAmount(((QuestionStatistic)entry.getValue()).getAmount());
      if (questionHistStatisticMap.containsKey(entry.getKey()))
      {
        int rightAmount = ((QuestionStatistic)questionHistStatisticMap.get(entry.getKey())).getRightAmount();
        int wrongAmount = ((QuestionStatistic)questionHistStatisticMap.get(entry.getKey())).getWrongAmount();
        int amount = ((QuestionStatistic)questionHistStatisticMap.get(entry.getKey())).getAmount();
        sr.setRightTimes(rightAmount);
        sr.setWrongTimes(wrongAmount);
        sr.setFinishRate(amount / ((QuestionStatistic)entry.getValue()).getAmount());
        sr.setRightRate(amount == 0 ? 0.0F : rightAmount / amount);
        finishRateList.add(Float.valueOf(sr.getFinishRate()));
        rightRateList.add(Float.valueOf(sr.getRightRate()));
      }
      else
      {
        finishRateList.add(Float.valueOf(0.0F));
        rightRateList.add(Float.valueOf(0.0F));
      }
      resultList.add(sr);
      Label label = new Label(sr.getPointName(), 1);
      titleList.add(label);
    }
    Gson gson = new Gson();
    model.addAttribute("sr", resultList);
    model.addAttribute("labels", gson.toJson(titleList));
    model.addAttribute("finishrate", gson.toJson(finishRateList));
    model.addAttribute("correctrate", gson.toJson(rightRateList));
    model.addAttribute("fieldList", this.questionService.getAllField(null));
    model.addAttribute("fieldId", Integer.valueOf(fieldId));
    return "usercenter";
  }
  
  @RequestMapping(value={"student/analysis"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userAnalysisDefaultPage(Model model, HttpServletRequest request)
  {
    List<Field> fieldList = this.questionService.getAllField(null);
    return "redirect:/student/analysis/" + ((Field)fieldList.get(0)).getFieldId();
  }
  
  @RequestMapping(value={"student/analysis/{fieldId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userAnalysisPage(Model model, HttpServletRequest request, @PathVariable int fieldId)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    model.addAttribute("lastLoginTime", userInfo.getLastLoginTime());
    Map<Integer, Map<Integer, QuestionStatistic>> questionMap = this.questionService.getTypeQuestionStaticByFieldId(fieldId);
    Map<Integer, Map<Integer, QuestionStatistic>> historyMap = this.questionHistoryService.getTypeQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
    
    List<KnowledgePointAnalysisResult> kparl = new ArrayList();
    for (Map.Entry<Integer, Map<Integer, QuestionStatistic>> entry : questionMap.entrySet())
    {
      KnowledgePointAnalysisResult kpar = new KnowledgePointAnalysisResult();
      kpar.setKnowledgePointId(((Integer)entry.getKey()).intValue());
      List<TypeAnalysis> tal = new ArrayList();
      int totalRightAmount = 0;
      int totalAmount = 0;
      for (Map.Entry<Integer, QuestionStatistic> entry1 :  entry.getValue().entrySet())
      {
        TypeAnalysis ta = new TypeAnalysis();
        ta.setQuestionTypeId(((Integer)entry1.getKey()).intValue());
        ta.setQuestionTypeName(((QuestionStatistic)entry1.getValue()).getQuestionTypeName());
        int rightAmount = 0;
        int wrongAmount = 0;
        try
        {
          rightAmount = ((QuestionStatistic)((Map)historyMap.get(entry.getKey())).get(entry1.getKey())).getRightAmount();
        }
        catch (Exception localException) {}
        try
        {
          wrongAmount = ((QuestionStatistic)((Map)historyMap.get(entry.getKey())).get(entry1.getKey())).getWrongAmount();
        }
        catch (Exception localException1) {}
        ta.setRightAmount(rightAmount);
        ta.setWrongAmount(wrongAmount);
        ta.setRestAmount(((QuestionStatistic)entry1.getValue()).getAmount() - rightAmount - wrongAmount);
        tal.add(ta);
        if (kpar.getKnowledgePointName() == null) {
          kpar.setKnowledgePointName(((QuestionStatistic)entry1.getValue()).getPointName());
        }
        totalRightAmount += rightAmount;
        totalAmount += ((QuestionStatistic)entry1.getValue()).getAmount();
      }
      kpar.setTypeAnalysis(tal);
      if (totalAmount > 0) {
        kpar.setFinishRate(totalRightAmount / totalAmount);
      }
      kparl.add(kpar);
    }
    model.addAttribute("kparl", kparl);
    model.addAttribute("fieldList", this.questionService.getAllField(null));
    model.addAttribute("fieldId", Integer.valueOf(fieldId));
    return "analysis";
  }
  
  @RequestMapping(value={"student/exam-history"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userExamHistPage(Model model, HttpServletRequest request)
  {
    int index = 1;
    if (request.getParameter("page") != null) {
      index = Integer.parseInt(request.getParameter("page"));
    }
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Page<ExamHistory> pageModel = new Page();
    
    pageModel.setPageNo(index);
    List<ExamHistory> hisList = this.examService.getUserExamHistByUserId(userInfo.getUserid(), pageModel, new int[] { 1, 2, 3 });
    model.addAttribute("hisList", hisList);
    String pageStr = PagingUtil.getPagelink(index, pageModel.getTotalPage(), "", "student/exam-history");
    model.addAttribute("pageStr", pageStr);
    return "exam-history";
  }
  
  @RequestMapping(value={"/user-detail/{userName}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String userInfoPage(Model model, HttpServletRequest request, @PathVariable("userName") String userName)
  {
    return "redirect:/student/usercenter";
  }
  
  class Label
  {
    public String text;
    public int max;
    
    public Label(String text, int max)
    {
      this.text = text;
      this.max = max;
    }
  }
  
  public class StatisticsResult
  {
    public int pointId;
    public String pointName;
    public int amount;
    public int rightTimes;
    public int wrongTimes;
    public float finishRate;
    public float rightRate;
    
    public StatisticsResult() {}
    
    public float getFinishRate()
    {
      return this.finishRate;
    }
    
    public void setFinishRate(float finishRate)
    {
      this.finishRate = finishRate;
    }
    
    public float getRightRate()
    {
      return this.rightRate;
    }
    
    public void setRightRate(float rightRate)
    {
      this.rightRate = rightRate;
    }
    
    public int getPointId()
    {
      return this.pointId;
    }
    
    public void setPointId(int pointId)
    {
      this.pointId = pointId;
    }
    
    public String getPointName()
    {
      return this.pointName;
    }
    
    public void setPointName(String pointName)
    {
      this.pointName = pointName;
    }
    
    public int getAmount()
    {
      return this.amount;
    }
    
    public void setAmount(int amount)
    {
      this.amount = amount;
    }
    
    public int getRightTimes()
    {
      return this.rightTimes;
    }
    
    public void setRightTimes(int rightTimes)
    {
      this.rightTimes = rightTimes;
    }
    
    public int getWrongTimes()
    {
      return this.wrongTimes;
    }
    
    public void setWrongTimes(int wrongTimes)
    {
      this.wrongTimes = wrongTimes;
    }
  }
}
